package com.eqdd.yiqidian.ui.yiqiyue;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.ListItem91Custom;
import com.eqdd.yiqidian.ListItem94Custom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.bean.rebuild.YueCommentBean;
import com.eqdd.yiqidian.box.ItemDecoration.DashDividerLineItemDecoration;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.box.span.NoLineClickSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.InputDialogActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ClickUtil;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;
import com.xujiaji.happybubble.BubbleDialog;
import com.xujiaji.happybubble.BubbleLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 17-12-25  上午9:57.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class CommentListActivity extends BaseActivity {

    private ListItem94Custom dataBinding;
    private boolean isMyComment;
    private int parentId;
    private String parentUserGuid;
    private int commentId;
    private String talkTo;
    private String talkContent;
    private int type;
    private MaterialDialog moreDialog;
    private int id;
    private int pageNum;
    private int firstCommentId;
    private SlimAdapterEx<YueCommentBean> slimAdapterEx;
    private YueCommentBean yueCommentBean;
    private MVCCoolHelper<List<YueCommentBean>> mvcHelper;
    private int dealPos;
    private boolean isCommentUp;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.list_item_94);
        initTopTitleBar(View.VISIBLE, "评论详情");
    }

    @Override
    public void initData() {
        yueCommentBean = (YueCommentBean) getIntent().getSerializableExtra(Config.BEAN);
        id = yueCommentBean.getArticleId();
        firstCommentId = yueCommentBean.getId();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.addItemDecoration(new DashDividerLineItemDecoration(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_88, new SlimInjector<YueCommentBean>() {
            @Override
            public void onInject(YueCommentBean data, IViewInjector injector) {
                injector.with(R.id.tv_content, view -> {
                    TextView textView = (TextView) view;
                    SpannableString spStr = new SpannableString(data.getUpname() + ":" + " @" + data.getParentUPname() + " " + data.getContent());
                    NoLineClickSpan firstSpan = new NoLineClickSpan("#3423ff", v -> {

                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getUserGuid());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    NoLineClickSpan secondSpan = new NoLineClickSpan("#3423ff", v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getParentUserGuid());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    spStr.setSpan(firstSpan, 0, data.getUpname().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), spStr.toString().indexOf("@") + 1 + data.getParentUPname().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    textView.setMovementMethod(LinkMovementMethod.getInstance());
                    textView.setText(spStr);
                });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    YueCommentBean dataItem = slimAdapterEx.getDataItem(position);
                    isMyComment = dataItem.getUserGuid().equals(AppConstent.user.getGuid());
                    parentId = dataItem.getId();
                    parentUserGuid = dataItem.getUserGuid();
                    commentId = dataItem.getId();
                    talkTo = dataItem.getUpname();
                    talkContent = dataItem.getContent();
                    type = 2;
                    isCommentUp=false;
                    dealPos = position;
                    showMoreDialog();
                })
                .setOnItemLongClickListener((recyclerView1, position, v) -> {
                    YueCommentBean dataItem = slimAdapterEx.getDataItem(position);
                    showReplyContent(v, dataItem.getFirstComment());
                    return true;
                });
        initView();
    }

    private void initView() {
        ImageUtil.setCircleImage(yueCommentBean.getIphoto(), dataBinding.ivHead);
        dataBinding.tvName.setText(yueCommentBean.getUpname());
        dataBinding.stvComment.setText(yueCommentBean.getCommentCount() + "");
        dataBinding.stvZan.setText(yueCommentBean.getZanCount() + "");
        dataBinding.stvZan.setEnabled(!yueCommentBean.isIsZan());
        dataBinding.stvZan.setEnabled(!yueCommentBean.isIsZan());
        if (yueCommentBean.isIsZan()) {
            dataBinding.stvZan.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
        } else {
            dataBinding.stvZan.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_hint));
            ClickUtil.click(dataBinding.stvZan, () -> {
                HttpUtil.zanComment(yueCommentBean.getId(), () -> {
                    yueCommentBean.setIsZan(true);
                    dataBinding.stvZan.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
                    dataBinding.stvZan.setEnabled(false);
                    dataBinding.stvZan.setText(yueCommentBean.getZanCount() + 1 + "");

                });
            });
        }
        dataBinding.stvComment.setDrawable(getResources().getDrawable(R.mipmap.ic_comment_hint));
        dataBinding.tvContent.setText(yueCommentBean.getContent());
        ClickUtil.click(dataBinding.stvComment, () -> {
            parentId = yueCommentBean.getId();
            talkTo = yueCommentBean.getUpname();
            parentUserGuid = yueCommentBean.getUserGuid();
            firstCommentId = yueCommentBean.getId();
            isCommentUp = true;
            talkTo();
        });
        ClickUtil.click(dataBinding.tvContent, () -> {
            isMyComment = yueCommentBean.getUserGuid().equals(AppConstent.user.getGuid());
            parentId = yueCommentBean.getId();
            parentUserGuid = yueCommentBean.getUserGuid();
            firstCommentId = yueCommentBean.getId();
            commentId = yueCommentBean.getId();
            talkTo = yueCommentBean.getUpname();
            talkContent = yueCommentBean.getContent();
            type = 1;
            isCommentUp = true;
            showMoreDialog();
        });

    }

    @Override
    public void setView() {

        ModelRx2DataSource<YueCommentBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<HttpResultRows<YueCommentBean>>post(HttpConfig.BASE_URL + HttpConfig.YUE_COMMENT_CHILDREN_LIST)
                        .params("page", pageNum)
                        .params("userGuid", AppConstent.user.getGuid())
                        .params("articleId", id)
                        .params("firstCommentId", firstCommentId)
                        .converter(new JsonConverter<HttpResultRows<YueCommentBean>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(listResultBean -> {
                            pageNum = listResultBean.getItems().getPage();
                            if (listResultBean.getStatus() == 200) {
                                return Flowable.just(listResultBean.getItems() == null ? new ArrayList<YueCommentBean>() : listResultBean.getItems().getRows());
                            } else {
                                ToastUtil.showShort(listResultBean.getMsg());
                                return Flowable.just(new ArrayList<>());
                            }
                        });

            }
        });
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    private void showMoreDialog() {
        if (moreDialog == null) {
            ArrayList<Object> objects = new ArrayList<>();
            objects.add("回复");
            objects.add("复制");
            objects.add("删除");
            SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                @Override
                public void onInject(Object data, IViewInjector injector) {

                    injector.text(R.id.tv_content, (String) data);
                }
            }).updateData(objects);
            moreDialog = new MaterialDialog.Builder(this)
                    .adapter(slimAdapterEx, new LinearLayoutManager(this))
                    .build();
            moreDialog.getRecyclerView().addItemDecoration(new SectionDividerItemDecoration(this)
                    .setHeadHeight(0)
                    .setRightPadding(DensityUtil.percentW(40))
                    .setLeftPadding(DensityUtil.percentW(40))
                    .setLastBootomHeght(0));
            ItemClickSupport.addTo(moreDialog.getRecyclerView())
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        switch (position) {
                            case 0:
                                talkTo();
                                break;
                            case 1:
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 将文本内容放到系统剪贴板里。
                                if (cm != null) {
                                    cm.setPrimaryClip(ClipData.newPlainText("Lable", talkContent));
                                }
                                ToastUtil.showShort("已复制");
                                break;
                            case 2:
                                HttpUtil.deleteComment(CommentListActivity.this, commentId, id, type, () -> {
                                    if (isCommentUp) {
                                        finish();
                                    } else {
                                        this.slimAdapterEx.getData().remove(dealPos);
                                        this.slimAdapterEx.notifyItemRemoved(dealPos);
                                    }
                                });
                                break;
                        }
                        moreDialog.dismiss();
                    });
        }
        SlimAdapterEx slimAdapterExMore = (SlimAdapterEx) moreDialog.getRecyclerView().getAdapter();
        if (isMyComment && slimAdapterExMore.getData().size() == 2) {
            slimAdapterExMore.getData().add("删除");
            slimAdapterExMore.notifyItemInserted(2);
        } else if (!isMyComment && slimAdapterExMore.getData().size() == 3) {
            slimAdapterExMore.getData().remove(2);
            slimAdapterExMore.notifyItemRemoved(2);
        }
        moreDialog.show();

    }

    private void talkTo() {
        Bundle bundle = new Bundle();
        bundle.putString(Config.TALK_TO, talkTo);
        startActivityForResult(InputDialogActivity.class, bundle, Config.INPUT);
    }

    private void showReplyContent(View view, String content) {
        ListItem91Custom inflate = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.list_item_91, null, false);
        inflate.tvContent.setText(content);
        BubbleLayout bl = new BubbleLayout(this);
        bl.setBubbleColor(Color.parseColor("#744e37"));
        bl.setShadowColor(Color.RED);
        bl.setLookLength(DensityUtil.percentW(15));
        bl.setLookWidth(DensityUtil.percentW(20));
        Rect viewRect = new Rect();
        view.getGlobalVisibleRect(viewRect);
        new BubbleDialog(this)
                .setClickedView(view)
                .addContentView(inflate.getRoot())
                .setPosition(viewRect.centerY() > (WindowUtil.csh >> 1) ? BubbleDialog.Position.TOP : BubbleDialog.Position.BOTTOM)
                .calBar(true)
                .setOffsetY(DensityUtil.percentW(viewRect.centerY() > (WindowUtil.csh >> 1) ? 15 : -15))
                .setBubbleLayout(bl)
                .setTransParentBackground()
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.INPUT && resultCode == Config.SUCCESS) {
            String content = data.getStringExtra(Config.CONTENT);
            HttpUtil.commentArticle(CommentListActivity.this, id, parentId, content, parentUserGuid, firstCommentId, (commentBean) -> {
                if (isCommentUp) {
                    slimAdapterEx.getData().add(0, (YueCommentBean) commentBean);
                    slimAdapterEx.notifyItemInserted(0);
                } else {
                    slimAdapterEx.getData().add((YueCommentBean) commentBean);
                    slimAdapterEx.notifyItemInserted(slimAdapterEx.getData().size() - 1);
                }
            });
        }
    }
}
